import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import { createVNode } from "vue";
import { clearAuthent } from "@/utils/auth";
import router from "@/router";
import permissionStore from "@/store/modules/permission";
let baseURL;
if (["production", "testing"].includes(process.env.NODE_ENV as string)) {
  baseURL = process.env.VUE_APP_BASE_API;
} else if (process.env.NODE_ENV === "development") {
  baseURL = process.env.VUE_APP_BASE_API;
}
const baseConfig = {
  baseURL,
  timeout: 60 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
};

const http = axios.create(baseConfig);

http.interceptors.request.use(
  (config: InternalAxiosRequestConfig<any>) => {
    if (!config.headers["Content-Type"]) config.headers["Content-Type"] = "application/json";
    const token = window.sessionStorage.getItem("token");
    if (token) config.headers["Authorization"] = token;
    config.headers["subdomain"] = window.location.host;
    // showLoading();
    return config;
  },
  (error: any) => {
    // hideLoading();
    return Promise.reject(error);
  }
);
// let isRefreshing = false;
let hasModal = false;
http.interceptors.response.use(
  async (response: AxiosResponse<any, any>) => {
    // hideLoading();
    if (response.status === 200) {
      if (Object.prototype.toString.call(response.data) === "[object Blob]") {
        if (response.config.headers.enable) return response;
        // 导出返回结果为 json 则表示报错
        // message.success(response.data && response.data.message);
      } else {
        if (response.data.code === 401) {
          if (!hasModal) {
            hasModal = true;
            Modal.confirm({
              title: "提示",
              icon: createVNode(ExclamationCircleOutlined),
              content: "身份信息过期，请重新登录",
              okText: "确认",
              cancelText: "取消",
              onOk() {
                // 重新登录
                directLogin();
                hasModal = false;
              },
              // eslint-disable-next-line @typescript-eslint/no-empty-function
              onCancel() {
                hasModal = false;
              }
            });
          }
        } else if (response.data.code === 400) {
          message.error(response.data.msg || "参数格式错误!");
        } else if (response.data.code === 200) {
          // message.success(response.data && response.data.message);
        } else {
          // message.error((response.data && response.data.message) || "其他错误");
          message.error(createVNode("pre", {}, (response.data && response.data.message) || "其他错误"));
        }
      }
    } else {
      message.error((response.data && response.data.message) || "其他错误");
    }
    // if (isTokenWillExpired()) {
    //   if (!isRefreshing) {
    //     try {
    //       isRefreshing = true;
    //       const refreshToken: string = getAuthent("refresh_token") || "";
    //       const user: string = getAuthent("user") || "";
    //       if (!user) {
    //         directLogin();
    //         throw new Error("登录超时!");
    //       }
    //       const res = await post("/sys/auth/refresh_token?refresh_token=" + refreshToken + "&username=" + JSON.parse(user).username, {});
    //       const { code } = res.data;
    //       if (code === 500) {
    //         directLogin();
    //       }
    //       const tokenInfo = res.data;
    //       setAuthent("token", tokenInfo.data.token || "");
    //       setAuthent("expiration_time", tokenInfo.data.expiration_time || "");
    //       setAuthent("refresh_token", tokenInfo.data.refresh_token || "");
    //     } catch (err) {
    //       console.warn(err);
    //       // directLogin();
    //     } finally {
    //       isRefreshing = false;
    //     }
    //     return response;
    //   }
    // }
    return response.data;
  },
  (err: any) => {
    // hideLoading();
    message.error(err.response.data.message || "其他错误");
    return Promise.reject(err);
  }
);
// 重新登录
const directLogin = () => {
  clearAuthent();
  permissionStore.asyncRoutes = [];
  router.replace({
    path: "/login",
    query: {
      redirect: (router.currentRoute as any).fullPath
    }
  });
};
export default http;
